import { Modal, Form, Input, message } from 'antd';
import Cookies from 'js-cookie';
import { useEffect, useMemo } from 'react';
import { history, useDispatch } from 'umi';

import type { FC } from 'react';

import { namespace } from '@/models/global';
import { editUserInfo, editUserPassword } from '@/services/login';
import type { SaasUserInfo } from '@/types/User';
import { getErrorMsg } from '@/util/utils';

interface Props {
  infoOrPassword: 'info' | 'password' | '';
  infoModalVisible: boolean;
  setInfoModalVisible: (t: boolean) => void;
}

interface ValueParams {
  password?: string;
  passwordConfirm?: string;
  oldPassword?: string;
  id?: string;
  mobileNo?: string;
  email?: string;
}
const EDIT_INFO = '编辑用户信息';
const EDIT_PASSWORD = '修改用户密码';
const USER_INFO: SaasUserInfo = JSON.parse(localStorage.getItem('USER_INFO') as string);
const InfoEditModal: FC<Props> = (props: Props) => {
  const dispatch = useDispatch();
  const { infoModalVisible, infoOrPassword, setInfoModalVisible } = props;
  const [formBean] = Form.useForm();
  const getTitle = useMemo(() => {
    if (infoOrPassword === 'info') return EDIT_INFO;
    return EDIT_PASSWORD;
  }, [infoOrPassword]);

  useEffect(() => {
    if (getTitle===EDIT_INFO) {
      formBean.setFieldsValue({
        name: USER_INFO.name,
        email: USER_INFO.email,
        mobileNo: USER_INFO.mobileNo,
      });
    }
  }, [getTitle]);

  const cancel = () => {
    if (getTitle===EDIT_PASSWORD) {
      formBean.resetFields();
    }
    setInfoModalVisible(false);
  };

  const handleOk = () => {
    const value: ValueParams = formBean.getFieldsValue();
    formBean.validateFields().then( async () => {
      if (getTitle===EDIT_INFO) {
        // 修改信息
        const res = await editUserInfo({
          ...value,
          id: USER_INFO.id,
        });
        if (res.code===200) {
          dispatch({
            type: `${namespace}/getUserInfo`,
            callback() {},
          });
          message.success('个人信息更新成功');
          setInfoModalVisible(false);
        } else {
          message.error(getErrorMsg(res));
        }
      } else if (getTitle===EDIT_PASSWORD) {
        // 修改用户密码
        const res = await editUserPassword({
          ...value,
          id: USER_INFO.id,
        });
        if (res.code===200) {
          setInfoModalVisible(false);
          localStorage.clear();
          Cookies.remove('saas_token'); // removed!
          setTimeout(() => {
            message.success('密码修改成功! 请重新登录');
            history.push('Login');
          }, 100);
        } else {
          message.error(getErrorMsg(res));
        }
      }

    });
  };

  return (
    <>
      <Modal destroyOnClose={true} title={getTitle} visible={infoModalVisible} onOk={handleOk} onCancel={cancel}>
        {
          getTitle === EDIT_INFO ?
            <div>
              <Form
                form={formBean}
                name="user_info"
              >
                <Form.Item
                  label={'姓名：'}
                  name="name"
                  rules={[{ required: true, message: '请输入姓名' }]}
                >
                  <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item
                  name="mobileNo"
                  label={'手机：'}
                  rules={[{ required: true, message: '请输入手机号' }]}
                >
                  <Input placeholder="请输入手机号"
                  />
                </Form.Item>
                <Form.Item
                  name="email"
                  label={'邮箱：'}
                  rules={[{ required: true, message: '请输入邮箱' }]}
                >
                  <Input placeholder="请输入邮箱"
                  />
                </Form.Item>
              </Form>
            </div>
            : getTitle === EDIT_PASSWORD ?
              <div>
                <Form
                  form={formBean}
                  name="edit_Password"
                >
                  <Form.Item
                    name="oldPassword"
                    rules={[{ required: true, message: '请输入旧密码' }]}
                  >
                    <Input type={'password'} placeholder="请输入旧密码" />
                  </Form.Item>
                  <Form.Item
                    name="password"
                    rules={[
                      { required: true, message: '请输入新密码' },
                      ({ getFieldValue }) => ({
                        validator(role: any, value: string) {
                          if (value === getFieldValue('oldPassword')) {
                            return Promise.reject('新密码不能与旧密码相同');
                          }
                          return Promise.resolve();
                        },
                      }),
                    ]}
                  >
                    <Input
                      type="password"
                      placeholder="请输入新密码"
                    />
                  </Form.Item>
                  <Form.Item
                    name="passwordConfirm"
                    rules={[
                      { required: true, message: '请再次输入新密码!' },
                      ({ getFieldValue }) => ({
                        validator(role: any, value: string) {
                          if (value !== getFieldValue('password')) {
                            return Promise.reject('密码不一致');
                          }
                          return Promise.resolve();
                        },
                      }),
                    ]}
                  >
                    <Input
                      type={'password'}
                      placeholder="请再次输入新密码"
                    />
                  </Form.Item>
                </Form>
              </div>
              : null
        }
      </Modal>
    </>
  );
};
export default InfoEditModal;
